<template>
    <div>
        <el-dialog v-model="dialogVisible" :title="trademarkParams.id ? '编辑' : '新增'" width="500"
            :before-close="handleClose" :close-on-click-modal="false">
            <el-form :model="trademarkParams" label-width="auto" style="max-width: 600px" :rules="rules" ref="formRef">
                <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                    <el-input placeholder="请您输入品牌名称" v-model="trademarkParams.tmName"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>

                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="handlerConfirm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang='ts'>
import { ref, reactive, watch } from 'vue'
import { ElMessage, UploadProps } from 'element-plus';
import { reqAddOrUpdateTrademark } from "@/api/product/trademark/index";
import type { TradeMark } from '@/api/product/trademark/type'
let dialogVisible = ref<boolean>(false)
//获取el-form组件实例
let formRef = ref();
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
    tmName: '',
    logoUrl: ''
})

const init = (obj: any) => {
    dialogVisible.value = true;
    if (obj.id) {
        Object.assign(trademarkParams, obj);
        console.log("trademarkParams",trademarkParams);
        
    } else {
        //清空收集数据
        trademarkParams.id = 0;
        trademarkParams.tmName = '';
        trademarkParams.logoUrl = '';
    }
}
defineExpose({
    init
})
const emit = defineEmits(["childClick"]);
//品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callBack: any) => {
    //是当表单元素触发blur时候,会触发此方法
    //自定义校验规则
    if (value.trim().length >= 2) {
        callBack();
    } else {
        //校验未通过返回的错误的提示信息
        callBack(new Error('品牌名称位数大于等于两位'))
    }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
    //如果图片上传
    if (value) {
        callBack();
    } else {
        callBack(new Error('LOGO图片务必上传'))
    }
}
//表单校验规则对象
const rules = {
    tmName: [
        //required:这个字段务必校验,表单项前面出来五角星
        //trigger:代表触发校验规则时机[blur、change]
        // { required: true, trigger: 'blur', validator: validatorTmName }
        { required: true, trigger: 'blur', message: '品牌名称位数大于等于两位' }
    ],
    logoUrl: [
        { required: true, validator: validatorLogoUrl }
    ]
}
watch(dialogVisible, (newV: any, oldV: any) => {
    if (newV == false) {
        // formRef.value.clearValidate();//清理某个字段的表单验证信息。
        formRef.value.resetFields();//重置该表单项，将其值重置为初始值，并移除校验结果
    }
})
const handleClose = () => {
    dialogVisible.value = false;
}
//对话框底部取消按钮
const cancel = () => {
    //对话框隐藏
    dialogVisible.value = false;
}
const handlerConfirm = async () => {
    //在你发请求之前,要对于整个表单进行校验
    //调用这个方法进行全部表单相校验,如果校验全部通过，在执行后面的语法
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateTrademark(trademarkParams);
    if (result.code == 200) {
        //对话框隐藏
        dialogVisible.value = false;
        //弹出提示信息
        ElMessage({
            type: 'success',
            message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功'
        });
        // getHasTrademark();
        emit("childClick");
    } else {
        //对话框隐藏
        dialogVisible.value = false;
        //添加品牌失败
        ElMessage({
            type: 'error',
            message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败'
        });
    }
}
//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
    //要求:上传文件格式png|jpg|gif 4M
    if (rawFile.type == 'image/png' || rawFile.type == 'image/jpeg' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于4M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: "上传文件格式务必PNG|JPG|GIF"
        })
        return false;
    }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    //response:即为当前这次上传图片post请求服务器返回的数据
    //收集上传图片的地址,添加一个新的品牌的时候带给服务器
    trademarkParams.logoUrl = response.data;
    //图片上传成功,清除掉对应图片校验结果
    formRef.value.clearValidate('logoUrl');

}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>